package com.geekaca.chat;

import java.io.*;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Set;

public class ServerRunnable implements Runnable {

    private Socket clientSocket;
    private InputStream ips;
    private DataInputStream dis;
    public ServerRunnable(Socket clientSocket) {
        this.clientSocket = clientSocket;
    }

    @Override
    public void run() {
        try {
            ips = clientSocket.getInputStream();
            dis = new DataInputStream(ips);

            while (true) {
                Set<Socket> sockets = ServerChat.onLineSocketMap.keySet();
                int msgType = dis.readInt();
                switch (msgType) {
                    case ChatConstants.MSG_TYPE_LOGIN:
                        String nickName = dis.readUTF();
                        System.out.println("login: " + clientSocket.getRemoteSocketAddress() + " nick: " + nickName);
                        ServerChat.onLineSocketMap.put(clientSocket, nickName);
                        ServerChat.names.append(nickName + ChatConstants.SPLIT);
                        sockets.forEach((curSocket) -> {
                            OutputStream myops = null;
                            try {
                                myops = curSocket.getOutputStream();
                                DataOutputStream mydos = new DataOutputStream(myops);
                                mydos.writeInt(ChatConstants.MSG_TYPE_LOGIN);
                                mydos.writeUTF(ServerChat.names.toString());
                                mydos.flush();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        });
                        break;

                    case ChatConstants.MSG_TYPE_CHAT:
                        String chat = dis.readUTF();
                        String msg = ServerChat.onLineSocketMap.get(clientSocket) + "说:" + chat;
                        System.out.println(ServerChat.onLineSocketMap.get(clientSocket) + "说:" + chat);
                        sockets.forEach((curSocket) -> {
                            OutputStream myops = null;
                            try {
                                myops = curSocket.getOutputStream();
                                DataOutputStream mydos = new DataOutputStream(myops);
                                Date date = new Date();
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                String formattedTimestamp = sdf.format(date);
                                mydos.writeInt(ChatConstants.MSG_TYPE_CHAT);
                                mydos.writeUTF(ServerChat.onLineSocketMap.get(clientSocket) + " " + formattedTimestamp +
                                        "\n  " + chat);
                                mydos.flush();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        });

                        break;

                    case ChatConstants.MSG_TYPE_CHAT_PRIVATE:
                        sendPrivate(dis);
                        break;

                    default:
                        throw new IllegalStateException("Unexpected value: " + msgType);
                }
            }
        } catch (IOException e) {
            System.out.println(" 发生异常　" + e.getMessage());
            e.printStackTrace();
        }
    }


    private void sendPrivate(DataInputStream dis) {
        System.out.println("服务器收到私聊信息: ");
        // 接收者昵称
        String nick = null;
        String privateMsg = null;
        try {
            nick = dis.readUTF();
            privateMsg = dis.readUTF();
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedTimestamp = sdf.format(date);

            Map<Socket, String> onLineSocketMap = ServerChat.onLineSocketMap;
            String fromNick = onLineSocketMap.get(clientSocket);
            privateMsg = fromNick + " 对你说: " + formattedTimestamp + "\n  " + privateMsg;

            String finalPrivateMsg = privateMsg;
            String finalNick = nick;
            onLineSocketMap.keySet().forEach((socket) -> {
                if (onLineSocketMap.get(socket).equals(finalNick)) {
                    System.out.println("的到要发私信的对象");
                    OutputStream privateOps = null;
                    try {
                        privateOps = socket.getOutputStream();
                        DataOutputStream mydos = new DataOutputStream(privateOps);
                        mydos.writeInt(ChatConstants.MSG_TYPE_CHAT_PRIVATE);
                        mydos.writeUTF(finalPrivateMsg);
                        mydos.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
